package com.yankaizhang.blog.security;

import com.yankaizhang.blog.entity.Log;
import com.yankaizhang.blog.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义登录成功处理器
 */
@Component
public class CustomAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Autowired
    LogService logService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
        Log log = new Log();
        log.setCreated(System.currentTimeMillis()/1000L);
        log.setContent("User: " + authentication.getName() + " 登陆成功");
        logService.save(log);
        request.getRequestDispatcher("/admin/index").forward(request, response);
    }
}
